/**
 * Created by wust on 2019-11-28 08:45:36
 * Copyright © 2019 wust. All rights reserved.
 */
package com.sc.common.util;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.util.Enumeration;

/**
 * @author: wust
 * @date: Created in 2019-11-28 08:45:36
 * @description:
 *
 */
public class NetworkUtil {
    private static Log logger = LogFactory.getLog(NetworkUtil.class);

    private NetworkUtil(){}

    public static String getLocalMac() throws SocketException, UnknownHostException {
        InetAddress ia = InetAddress.getLocalHost();

        //获取网卡，获取地址
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
        StringBuffer sb = new StringBuffer();
        for(int i=0; i<mac.length; i++) {
            if(i != 0) {
                sb.append("-");
            }
            //字节转换为整数
            int temp = mac[i]&0xff;
            String str = Integer.toHexString(temp);
            if(str.length()==1) {
                sb.append("0"+str);
            }else {
                sb.append(str);
            }
        }
        return sb.toString();
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        logger.info("x-forwarded-for ip: " + ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            logger.info("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            logger.info("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            logger.info("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            logger.info("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
            logger.info("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            logger.info("getRemoteAddr ip: " + ip);
        }

        if("127.0.0.1".equals(ip)){
            String ip1 = getHostIp();
            if(ip1 != null){
                return ip1;
            }
        }
        return ip;
    }

    public static String getIpAddressByServerHttpRequest(ServerHttpRequest request) {
        String ip = MyStringUtils.null2String(request.getHeaders().get("x-forwarded-for"));
        logger.info("x-forwarded-for ip: " + ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = MyStringUtils.null2String(request.getHeaders().get("Proxy-Client-IP"));
            logger.info("Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = MyStringUtils.null2String(request.getHeaders().get("WL-Proxy-Client-IP"));
            logger.info("WL-Proxy-Client-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = MyStringUtils.null2String(request.getHeaders().get("HTTP_CLIENT_IP"));
            logger.info("HTTP_CLIENT_IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = MyStringUtils.null2String(request.getHeaders().get("HTTP_X_FORWARDED_FOR"));
            logger.info("HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip =  MyStringUtils.null2String(request.getHeaders().get("X-Real-IP"));
            logger.info("X-Real-IP ip: " + ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = MyStringUtils.null2String(request.getRemoteAddress().toString());
            logger.info("getRemoteAddr ip: " + ip);
        }

        if("127.0.0.1".equals(ip)){
            String ip1 = getHostIp();
            if(ip1 != null){
                return ip1;
            }
        }
        return ip;
    }

    public static String getHostIp(){
        try{
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()){
                NetworkInterface netInterface = allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress ip = addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":") == -1){
                        return ip.getHostAddress();
                    }
                }
            }
        }catch(Exception e){
            logger.error("获取本机IP地址出错",e);
        }
        return null;
    }
}
